//
//  BookInfoViewController.m
//  ZYTS-iPhone
//
//  Created by yuzhou on 12-12-9.
//  Copyright (c) 2012年 wzyk. All rights reserved.
//

#import "BookInfoViewController.h"
#import "UIImageView+WebCache.h"
#import "AuthorManager.h"
#import "AccountViewController.h"
#import "ShareViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "SinaWeiboManager.h"

@interface BookInfoViewController ()

@end

@implementation BookInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotBookInfo:) name:gotBookInfoNotify object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(collectBook:) name:collectBookNotify object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotBookContent:) name:gotBookContentNotify object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self showLoadingView];
    [[DataRequest sharedRequest] getBookInfoByID:self.itemid];
    
    coverImageView.layer.shadowColor = [UIColor blackColor].CGColor;
    coverImageView.layer.shadowOpacity = 0.45f;
    coverImageView.layer.shadowOffset = CGSizeMake(0, 3);
    coverImageView.layer.masksToBounds = NO;
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:coverImageView.bounds];
    coverImageView.layer.shadowPath = path.CGPath;
}

- (void)gotBookInfo:(NSNotification *)notification
{
    [self removeloadingView];
    if ([notification.object isKindOfClass:[NSDictionary class]]) {
        NSDictionary *result = [notification.object valueForKey:@"result"];
        if ([result isKindOfClass:[NSDictionary class]]) {
            self.bookInfo = result;
            NSString *imageURL = [[self.bookInfo valueForKey:@"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [coverImageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"default_image"] options:SDWebImageRetryFailed];
            artistLabel.text = [self.bookInfo valueForKey:@"broadcaster"];
            chapterLabel.text = [NSString stringWithFormat:@"%@",[self.bookInfo valueForKey:@"sub_count"]];
            sharedLabel.text = [NSString stringWithFormat:@"%@",[self.bookInfo valueForKey:@"share_count"]];
            collectedLabel.text = [NSString stringWithFormat:@"%@",[self.bookInfo valueForKey:@"favorite_count"]];
            commentedLabel.text = [NSString stringWithFormat:@"%@",[self.bookInfo valueForKey:@"comment_count"]];
            [self setRate:[[self.bookInfo valueForKey:@"item_rank"] intValue]];
            
            NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"</?[^>]+/?>"
                                                                                   options:NSRegularExpressionCaseInsensitive
                                                                                     error:nil];
            NSString *description = [self.bookInfo valueForKey:@"description"];
            if (description) {
                NSArray *array = [regex matchesInString:description options:0 range:NSMakeRange(0, description.length)];
                for (NSTextCheckingResult *result in array) {
                    NSLog(@">>>%@",[description substringWithRange:result.range]);
                }
                description = [regex stringByReplacingMatchesInString:description options:0 range:NSMakeRange(0, [description length]) withTemplate:@""];
                descriptionTextView.text = description;
            }
            
            shareButton.enabled = YES;
            [shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
            //下面这段代码是迫不得已的
            //把听书信息保存在本地，后来的已下载界面要用到
            NSMutableDictionary *bookDic = [NSMutableDictionary dictionary];
            NSArray *keyArray = [NSArray arrayWithObjects:@"item_id",@"item_name",@"image",@"sub_count", nil];
            for (NSString *key in keyArray) {
                [bookDic setValue:[_bookInfo valueForKey:key] forKey:key];
            }
            
            NSMutableDictionary *coverDic = [[NSUserDefaults standardUserDefaults] objectForKey:kCoverImage];
            if (coverDic == nil) {
                coverDic = [NSMutableDictionary dictionary];
            }
            else {
                coverDic = [NSMutableDictionary dictionaryWithDictionary:coverDic];
            }
            [coverDic setObject:bookDic forKey:_itemid];
            [[NSUserDefaults standardUserDefaults] setObject:coverDic forKey:kCoverImage];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
}

- (void)setRate:(int)rate
{
    rateLabel.text = [NSString stringWithFormat:@"%d分",rate];
    for (int i = 0; i < 5; i++) {
        UIImageView *starView = (UIImageView *)[[rateView subviews] objectAtIndex:i];
        if (i * 2 + 2 <= rate) {
            starView.image = [UIImage imageNamed:@"fullStar.png"];
        }
        else if (i * 2 + 1 <= rate) {
            starView.image = [UIImage imageNamed:@"halfStar.png"];
        }
        else {
            starView.image = [UIImage imageNamed:@"emptyStar.png"];
        }
    }
    rateView.hidden = NO;
}

- (void)collectBook:(NSNotification *)notification {
//    [[[[UIAlertView alloc] initWithTitle:nil
//                                 message:[[[notification object] objectForKey:@"result"] objectForKey:@"state_message"]
//                                delegate:nil
//                       cancelButtonTitle:@"确定"
//                       otherButtonTitles:nil] autorelease] show];
    
    ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:[[[notification object] objectForKey:@"result"] objectForKey:@"state_message"]] autorelease];
    [promptView show];
}

- (void)gotBookContent:(NSNotification *)notification
{
    if ([notification.object isKindOfClass:[NSDictionary class]]) {
        NSArray *result = [notification.object valueForKey:@"result"];
        if ([result isKindOfClass:[NSArray class]]) {
            self.contentArray = result;
            downloadButton.enabled = YES;
            [downloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }
    }
}

- (IBAction)downloadAction:(id)sender
{
    if (![[AuthorManager defaultManager] hasLoggedIn]) {
        AccountViewController *accountViewController = [[[AccountViewController alloc] initWithNibName:@"AccountViewController" bundle:nil] autorelease];
        accountViewController.needLogin = YES;
        [self.view.window.rootViewController presentViewController:accountViewController animated:YES completion:nil];
        return;
    }
    else if (![[AuthorManager defaultManager] hasUserPaid]) {
        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"183read.com" message:@"离线功能仅限中邮阅读网付费用户" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil] autorelease];
        [alertView show];
        return;
    }
    if (![[DownloadManager defaultManager] isConnectionEnable]) {
        ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"无网络连接"] autorelease];
        [promptView show];
        return;
    }
    else if ([[DownloadManager defaultManager] isWWANEnable]) {
        if (![[DownloadManager defaultManager] WWANDownloadEnable]) {
            UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"当前为2G/3G网络" message:@"您可在设置中允许使用2G/3G网络" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"仍然下载", nil] autorelease];
            [alertView show];
        }
        return;
    }
    for (NSDictionary *content in self.contentArray) {
        [[DownloadManager defaultManager] downloadBook:content];
    }
    ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"已加入下载列表"] autorelease];
    [promptView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        for (NSDictionary *content in self.contentArray) {
            [[DownloadManager defaultManager] downloadBook:content];
        }
        ABPromptView *promptView = [[[ABPromptView alloc] initWithTitle:@"已加入下载列表"] autorelease];
        [promptView show];
    }
}

- (IBAction)onClickShareBtn:(id)sender {
    if ([[[SinaWeiboManager defaultManager] sinaweibo] isLoggedIn]) {
        ShareViewController *shareViewController = [[[ShareViewController alloc] initWithNibName:@"ShareViewController" bundle:nil] autorelease];
        shareViewController.info = _bookInfo;
        shareViewController.shareType = ShareTypeSinaWeibo;
        UINavigationController *navController = (UINavigationController *)self.view.window.rootViewController;
        [navController pushViewController:shareViewController animated:YES];
    } else {
        [[[SinaWeiboManager defaultManager] sinaweibo] logIn];
    }
}

- (IBAction)onClickCollectBtn:(id)sender {
    if ([[AuthorManager defaultManager] hasLoggedIn]) {
        [[DataRequest sharedRequest] collectBook:[[AuthorManager defaultManager] userID]
                                        username:[[AuthorManager defaultManager] username]
                                          bookID:[self.bookInfo objectForKey:@"item_id"]];
    } else {
        AccountViewController *accountViewController = [[[AccountViewController alloc] initWithNibName:@"AccountViewController" bundle:nil] autorelease];
        accountViewController.needLogin = YES;
        accountViewController.wantsFullScreenLayout = YES;
        [self.view.window.rootViewController presentViewController:accountViewController animated:YES completion:nil];
        
    }
}

- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:self.view.bounds] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [coverImageView release];
    [artistLabel release];
    [chapterLabel release];
    [sharedLabel release];
    [collectedLabel release];
    [commentedLabel release];
    [rateView release];
    [rateLabel release];
    [descriptionTextView release];
    [_itemid release];
    [_bookInfo release];
    [_contentArray release];
    [downloadButton release];
    [shareButton release];
    [super dealloc];
}
- (void)viewDidUnload {
    [coverImageView release];
    coverImageView = nil;
    [artistLabel release];
    artistLabel = nil;
    [chapterLabel release];
    chapterLabel = nil;
    [sharedLabel release];
    sharedLabel = nil;
    [collectedLabel release];
    collectedLabel = nil;
    [commentedLabel release];
    commentedLabel = nil;
    [rateView release];
    rateView = nil;
    [rateLabel release];
    rateLabel = nil;
    [descriptionTextView release];
    descriptionTextView = nil;
    [downloadButton release];
    downloadButton = nil;
    [shareButton release];
    shareButton = nil;
    [super viewDidUnload];
}

@end
